import 'package:flutter/foundation.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/presentation/players/add_player_page/widgets/my_circle_avatar.dart';
import 'package:syria_sports/presentation/coaches/coach_profile_screen/coach_profile_screen.dart';
import 'package:syria_sports/widgets/screen_state_widget.dart';

import '../../../core/utils/show_toast.dart';
import '../../../data/controllers/notes_controller.dart';
import '../../../dialogs/add_note_dialog.dart';
import '../../../dialogs/delete_player_confirmation.dart';
import '../../../widgets/app_bar/appbar_subtitle.dart';
import '../../../widgets/app_bar/custom_app_bar.dart';
import '../../../widgets/app_bar/outline_icon_button.dart';
import '../../exercises/exercises_page/models/exercise.dart';
import '../models/note_model.dart';
import 'coach_notes_cubit.dart';
import 'package:flutter/material.dart';


class CoachNotesScreen extends StatelessWidget {
  final Exercise exercise;
  const CoachNotesScreen({Key? key, required this.exercise}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(ImageConstant.imgBackground),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        appBar: _buildAppBar(context:context),
        body: BlocProvider<CoachNotesCubit>(
          create: (context) => CoachNotesCubit()..init(exercise: exercise),
          child: BlocConsumer<CoachNotesCubit, CoachNotesState>(
            listener: (context, state) {
              // TODO: implement listener
            },
            builder: (context, state) {
              var cubit = CoachNotesCubit.get(context);

              return SizedBox(
                height: height,
                width: width,
                child: ScreenStateWidget(
                  isLoading: state is CoachNotesLoading,
                  isError: state is CoachNotesError,
                  isDone: state is CoachNotesDone,
                  onRefresh: cubit.getAllNotes,
                  onDone: Column(
                    children: [
                      Expanded(
                        child: ListView.builder(
                          itemCount: cubit.notes.length,
                          reverse: true,
                          itemBuilder: (context, index) {
                            final note = cubit.notes[index];
                            return _buildNoteItem(note , cubit,context);
                          },
                        ),
                      ),
                      const SizedBox(height: 32),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildNoteItem(NoteModel note ,CoachNotesCubit cubit,BuildContext context) {
    final isMyNote = PrefUtils.getUserId() == note.user?.userId;
    const String dateTimeFormatPattern = 'yyyy-MM-dd hh:mm';

    return Padding(
      padding:const EdgeInsets.only(bottom:14),
      child: Slidable(
        enabled: isMyNote || PrefUtils.isAdmin(),
        endActionPane:!isMyNote? null: ActionPane(
          motion: const ScrollMotion(),
          extentRatio: .5,
          children: [
            SlidableAction(
              onPressed: (context){
                showDeleteConfirmation(context, note, cubit);
              },
              backgroundColor: Colors.transparent,
              foregroundColor: Colors.red,
              icon: Icons.delete,
              label: 'حذف',
            ),

          ],
        ),
        startActionPane:isMyNote? null: ActionPane(
          motion: const ScrollMotion(),
          extentRatio: .5,
          children: [
            SlidableAction(
              onPressed: (context){
                showDeleteConfirmation(context, note, cubit);
              },
              backgroundColor: Colors.transparent,
              foregroundColor: Colors.red,
              icon: Icons.delete,
              label: 'حذف',
            ),

          ],
        ),
        child: Container(
          margin: const EdgeInsets.symmetric(vertical: 0.0, horizontal: 16.0),
          alignment: isMyNote ? Alignment.centerLeft : Alignment.centerRight,
          child: Column(
            crossAxisAlignment:
            isMyNote ? CrossAxisAlignment.end : CrossAxisAlignment.start,
            children: [
              /*Text(
                (note.exercise?.name)??"",
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16.0,
                ),
              ),*/
              if(!isMyNote)
              const SizedBox(height: 4.0),
              if(!isMyNote)
              InkWell(
                onTap: (){
                  if(note.user!= null) {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => CoachProfileScreen.builder(context, note.user!)));
                  }
                },
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    MyCircleAvatar(
                      borderColor: Colors.red,
                      backgroundColor:Theme.of(context).colorScheme.onPrimaryContainer,
                      width: 14,
                      editMode: false,
                      imageURL:note.user?.image,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      (note.user?.fullName)??"",
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12.0,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 8.0),
              Container(
                margin:EdgeInsets.only(left:!isMyNote?32:0 , right:isMyNote?32:0 ),
                padding: const EdgeInsets.all(8.0),
                decoration: BoxDecoration(
                  color: isMyNote ? Theme.of(context).colorScheme.secondary : Colors.grey[200],
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: Column(
                  crossAxisAlignment:
                  isMyNote ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                  children: [
                    Text(
                      note.text,
                      style: TextStyle(
                        fontSize: 14.0,
                        color: isMyNote? Colors.white : Colors.black,
                      ),
                    ),
                    const SizedBox(height: 16.0),
                    Text(
                      '${note.createAt?.format(dateTimeFormatPattern)}',
                      style: TextStyle(
                        color: isMyNote? Colors.white : Colors.black,
                        fontSize: 12.0,
                      ),
                    ),
                  ],
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }
  PreferredSizeWidget _buildAppBar({required BuildContext context}) {
    return CustomAppBar(
      leading: OutlineIconButton(
        imagePath: ImageConstant.imgRightIcon,
        onTapped: (){
          Navigator.pop(context);
        },
      ),
      actions: [
        if (PrefUtils.isAdmin())
          OutlineIconButton(
            icon: Icons.add,
            margin:const EdgeInsets.all(8),
            padding:const EdgeInsets.all(2),
            onTapped: ()async{

                //if(kDebugMode) {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AddNoteDialog(gymExercise:exercise ,);
                    },
                  );
                /*}else{
                  showMessage('هذه الخدمة غير متاحة في الاصدار التجريبي');
                }*/
            },
          ),
      ],
      title: AppbarSubtitle(
        text: "ملاحظات التمرين", margin: EdgeInsets.only(left: 12.h),
      ),
    );
  }

  void showDeleteConfirmation(BuildContext context, NoteModel player , CoachNotesCubit cubit) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return DeleteConfirmationDialog(
          playerName: (player.user?.fullName)??'',
          titleUser: 'ملاحظة المدرب',
          onConfirm: (){
            NotesController.deleteById(player.noteId??'-1').then((value) {
              if(value?.state == true){
                cubit.getAllNotes();
              }
            });

          },
        );
      },
    );
  }
}
